<?php

/**
 * TomatoCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version 	$Id: CategoryController.php 4929 2010-08-25 03:36:50Z huuphuoc $
 * @since		2.0.0
 */
class Category_CategoryController extends Zend_Controller_Action {
    /* ========== Backend actions =========================================== */

    /**
     * Add new category
     *
     * @return void
     */
    public function addAction() {
        /**
         * Changed by Tronghm
         */
        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        $lang = $this->getRequest()->getParam('lang', Tomato_Config::getConfig()->web->lang);
        $categoryModel->setLang($lang);
        $categories = $categoryModel->getTree();
        $this->view->assign('categories', $categories);
        $request = $this->getRequest();
        $sourceId = $request->getParam('source_id');
        $sourceCategory = (null == $sourceId) ? null : $categoryModel->getById($sourceId);
        $this->view->assign('sourceCategory', $sourceCategory);
        $this->view->assign('lang', $request->getParam('lang'));
        if ($request->isPost()) {
            $user = Zend_Auth::getInstance()->getIdentity();
            $purifier = new HTMLPurifier();
            $category = new Category_Models_Entities_Category(array(
                'name' => $purifier->purify($request->getPost('name')),
                'slug' => $request->getPost('slug'),
                'module_name' => $request->getPost('module_name'),
                'created_date' => date('Y-m-d H:i:s'),
                'user_id' => $user->id,
                'parent_id' => $request->getPost('parent_id'),
                'language' => $request->getPost('language'),
                'description' => $request->getPost('description'),
                'actived' => $request->getPost('actived'),
                'featured' => $request->getPost('featured'),
                'meta_title' => $purifier->purify($request->getPost('meta_title')),
                'meta_description' => $purifier->purify($request->getPost('meta_description')),
                'meta_keywords' => $purifier->purify($request->getPost('meta_keywords'))
            ));
            $id = $categoryModel->add($category);
            if ($id) {
                /**
			 * @since 2.0.8
			 */
			$source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));
			$translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
			$translationModel->add(new Core_Models_Entities_Translation(array(
				'item_id' 	      => $id,
				'item_class'      => get_class($category),
				'source_item_id'  => ('' == $source['id']) ? $id : $source['id'],
				'language'        => $category->language,
				'source_language' => ('' == $source['language']) ? null : $source['language'],
			)));
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('success:'.$this->view->translate('category_add_success'));
                $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'category_category_add'));
            } else {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:'.$this->view->translate('category_add_error'));
            }
        }
    }

    /**
     * Edit category
     *
     * @return void
     */
    public function editAction() {
        try {
            $request = $this->getRequest();
            /**
             * Changed by Tronghm
             */
            $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
            $categoryModel->setLang(Tomato_Config::getConfig()->localization->languages->default);
            $categoryId = $request->getParam('id');
            $category = $categoryModel->getById($categoryId);

            if (null == $category) {
                throw new Exception('Not found category with id of ' . $categoryId);
            }
            $sourceCategory = $categoryModel->getSource($category);
            $this->view->assign('sourceCategory', $sourceCategory);
            $this->view->assign('category', $category);
            $parentCategories = $categoryModel->getTree();
            $this->view->assign('parentCategories', $parentCategories);

            if ($request->isPost()) {
                $purifier = new HTMLPurifier();
                $category = new Category_Models_Entities_Category(array(
                    'id' => $categoryId,
                    'name' => $purifier->purify($request->getPost('name')),
                    'slug' => $request->getPost('slug'),
                    'module_name' => $request->getPost('module_name'),
                    'modified_date' => date('Y-m-d H:i:s'),
                    'language' => $request->getPost('language'),
                    'description' => $request->getPost('description'),
                    'actived' => $request->getPost('actived'),
                    'featured' => $request->getPost('featured'),
                    'meta_title' => $purifier->purify($request->getPost('meta_title')),
                    'meta_description' => $purifier->purify($request->getPost('meta_description')),
                    'meta_keywords' => $purifier->purify($request->getPost('meta_keywords'))
                ));

                $parentId = $request->getPost('parent_id');
                if ($parentId != 1) {
                    /**
                     * Get parent category
                     */
                    $parent = $categoryModel->getById($category->parent_id);
                    if ($parent != null && $parent->id == $parentId) {
                        /**
                         * User do NOT change the parent category value
                         */
                        $categoryModel->edit($category);
                        $this->_helper->getHelper('FlashMessenger')
                                ->addMessage($this->view->translate('category_edit_success'));
                        $this->_redirect($this->view->serverUrl() . $this->view->url(array('id' => $categoryId), 'category_category_edit'));
                    } else {
                        /**
                         * User changed parent category
                         */
                        if (!$categoryModel->delete($category)) {
                            $this->_helper->getHelper('FlashMessenger')
                                    ->addMessage($this->view->translate('category_edit_error'));
                        } else {
                            $params['parent_id'] = $parentId;
                            if ($categoryModel->add($category)) {
                                $this->_helper->getHelper('FlashMessenger')
                                        ->addMessage('success:'.$this->view->translate('category_edit_success'));
                                $this->_redirect($this->view->serverUrl() . $this->view->url(array('id' => $categoryId), 'category_category_edit'));
                            } else {
                                $this->_helper->getHelper('FlashMessenger')
                                        ->addMessage('error:'.$this->view->translate('category_edit_error'));
                            }
                        }
                    }
                }

                /**
                 * @since 2.0.8
                 */
//            $source = Zend_Json::decode($request->getPost('sourceItem', '{"id": "", "language": ""}'));
//            $translationModel = Tomato_Model_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
//            $translationModel->setDbConnection($conn);
//            $translationModel->update(new Core_Models_Translation(array(
//                        'item_id' => $categoryId,
//                        'item_class' => get_class($category),
//                        'source_item_id' => ('' == $source['id']) ? $categoryId : $source['id'],
//                        'language' => $category->language,
//                        'source_language' => ('' == $source['language']) ? null : $source['language'],
//                    )));
            }
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    /**
     * Delete category
     *
     * @return void
     */
    public function deleteAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $response = 'RESULT_ERROR';
        $request = $this->getRequest();
        if ($request->isPost()) {
            $id = $request->getPost('id');
            /**
             * Changed by TrongHM
             */
            $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
            $ids = array();
            if (is_numeric($id)) {
                $ids[] = $id;
            } else {
                $ids = Zend_Json::decode($id);
            }
            foreach ($ids as $categoryId) {
                $category = $categoryModel->getById($categoryId);
                if ($category != null) {
                    $categoryModel->delete($category);
                    /**
                     * @since 2.0.8
                     */
                    $translationModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getTranslationModel();
                    $translationModel->delete($categoryId, get_class($category));

                    $response = 'RESULT_OK';
                }
            }
        }
        $this->getResponse()->setBody($response);
    }

    /**
     * List categories
     *
     * @return void
     */
    public function listAction() {
        /**
         * Changed by Tronghm
         */
        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        $lang = $this->getRequest()->getParam('lang', Tomato_Config::getConfig()->web->lang);
        $categoryModel->setLang($lang);

        $categories = $categoryModel->getTree();
        $this->view->assign('categories', $categories);
    }

    /**
     * Update categories' order
     *
     * @since 2.0.7
     * @return void
     */
    public function orderAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $response = 'RESULT_ERROR';
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = $request->getPost('data');
            $data = Zend_Json::decode($data);

            $conn = Tomato_Db_Connection::factory()->getMasterConnection();
            $categoryModel = Tomato_Model_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
            $categoryModel->setDbConnection($conn);

            foreach ($data as $category) {
                $categoryModel->updateOrder(new Category_Models_Category(array(
                            'category_id' => $category['id'],
                            'parent_id' => $category['parent_id'],
                            'left_id' => $category['left_id'],
                            'right_id' => $category['right_id'],
                        )));
            }

            $response = 'RESULT_OK';
        }
        $this->getResponse()->setBody($response);
    }

    /**
     * Check existed name
     */
    public function checkAction(){
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();
        $request = $this->getRequest();
        $name = $request->getParam('name');
        $categoryModel = Rabbit_Model_Factory::getInstance()->setModule('category')->getCategoryModel();
        if($categoryModel->exist($name)){
            $this->getResponse()->setBody('false');
        }  else {
           $this->getResponse()->setBody('true');
        }
    }

}

